<template>
	<view class="cart-page">

		<view style="height: max-content;background-color: #FFFFFF;padding: 20upx 30upx 20upx 30upx;"
			class="flex justify-between" @tap="toShoppAddress(addrForm.id)">
			<view>
				<view style="display: flex;height: 50upx;" class="align-center">
					<view style="font-size: 30upx;color: #4d4d4d;font-weight: 600;">
						<text class="lg margin-right-sm cuIcon-locationfill"></text>
						{{addrForm.detailAddress?addrForm.detailAddress: '暂无地址，请添加...'}}
					</view>
				</view>
				<view style="display: flex;" class="align-center">
					<view style="font-size: 24upx;color: #4d4d4d;">{{addrForm.name?addrForm.name:''}}</view>
					<view style="font-size: 24upx;color: #4d4d4d;margin-left: 20upx;text-align: right;">
						{{addrForm.phone?addrForm.phone:''}}
					</view>
				</view>
			</view>
			<view style="font-size: 30upx;" class="flex align-center justify-center">
				<text class="lg text-black cuIcon-right"></text>
			</view>
		</view>
		<!-- 商品列表 -->
		<view class="cart-list">
			<view v-for="(item, index) in cartList" :key="index" class="cu-item flex align-center"
				style="position: relative;">
				<!-- 店铺信息（左） -->
				<!-- <view class="shop-info" slot="left">
					<text class="shop-name">{{ item.shopName }}</text>
					<text class="arrow">></text>
				</view> -->
				<!-- 商品内容（中） -->
				<view class="goods-content ">
					<image class="goods-img" :src="item.image" mode="aspectFill"></image>
					<view class="goods-info-wrap">
						<!-- 商品标题 -->
						<text class="goods-title">{{ item.title }}</text>
						<view class="goods-spec">
							<cu-tag v-for="(tag, tagIdx) in item.skuAttr" style="margin-right: 10rpx;" :key="tagIdx">
								{{ tag }}
							</cu-tag>
						</view>
						<!-- 价格区域 -->
						<view class="price-section">
							<text class="current-price">券后¥{{ item.price }}</text>
							<text class="discount">合计¥{{ item.totalPrice }}</text>
							<!-- <text class="detail">明细</text> -->
						</view>
						<!-- 优惠券说明 -->
						<!-- <text class="coupon-desc">{{ item.couponInfo }}</text> -->
					</view>


				</view>
				<view style="position: absolute;right: 15rpx;top: 10rpx;height: 30rpx;text-align: center;">
					x{{item.count}}
				</view>

			</view>
		</view>

		<!-- 备注 -->
		<view class="bg-white">
			<view class="padding ">
				<view class="text-30" style="color: #1E1F31;margin-right: 20upx;font-weight: bold;">备注说明</view>
				<textarea v-model="note" class="text-white text-df flex-sub padding-tb-sm " placeholder="请输入备注说明..."
					style="height: 200upx;"></textarea>
			</view>
		</view>




		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="total">
				合计: <text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<!-- <cu-btn class="settle-btn" @tap="showPay = true">去结算</cu-btn> -->
			<cu-btn class="settle-btn" @tap="submitOrder">去结算</cu-btn>
		</view>



		<view class="cu-load load-modal" v-if="loadModal">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<!-- <image src="/static/logo.png" mode="aspectFit"></image> -->
			<view class="gray-text">加载中...</view>
		</view>





		<view class="box" v-if="showPay">
			<view class="bottbox">
				<view class="flex align-start justify-between">
					<view
						style="width: 100%;text-align: center;font-size:38rpx;font-weight: bold;margin-top:15rpx;margin-bottom: 80rpx;">
						选择支付方式
					</view>
					<view class="margin-right margin-top-sm" @click="bindclost">
						<image src="../../static/images/msg/close.png" style="width: 30upx;height: 30upx;">
						</image>
					</view>
				</view>
				<view style="display: flex;" v-for="(item,index) in openLists" :key='index'>
					<view style="width: 100%;display: flex;height: 100upx;align-items: center;padding: 20upx 30rpx;"
						v-if="item.text === '零钱' && czSel != '否'">
						<view style="display: flex;width:80%;align-items: center;">
							<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{item.text}}
							</view>
						</view>
						<view style="width: 20%;display: flex;justify-content: flex-end;">
							<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item.id)'>
								<label class="tui-radio">
									<radio color="#1789FD" :checked="openWay === item.id ? true : false" />
								</label>
							</radio-group>
						</view>
					</view>
					<view style="width: 100%;display: flex;height: 100upx;align-items: center;padding: 20upx 30rpx;"
						v-if="item.text != '零钱'">
						<view style="display: flex;width:80%;align-items: center;">
							<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
							<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{item.text}}
							</view>
						</view>
						<view style="width: 20%;display: flex;justify-content: flex-end;">
							<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item.id)'>
								<label class="tui-radio">
									<radio color="#1789FD" :checked="openWay === item.id ? true : false" />
								</label>
							</radio-group>
						</view>
					</view>
				</view>
				<view
					style="width: 690rpx;height: 80rpx;background:#1789FD;color:#FFFFFF;text-align: center;line-height: 80rpx;border-radius: 50rpx;margin: 30rpx;"
					@click="pay()">确认支付</view>
			</view>

		</view>


	</view>
</template>
<script>
	export default {
		data() {
			return {
				// 购物车商品列表（模拟数据）
				cartList: [],
				isAllChecked: false, // 全选状态
				totalPrice: 0, // 选中商品总价


				loadModal: false,

				addrForm: {},

				submitOrderForm: {},


				openLists: [], //支付方式列表
				showPay: false,
				openWay: '', //支付方式
				isPay: true,
				note: '', //备注
				fare: '', //运费
			}
		},
		onLoad(option) {
			
			this.submitOrderForm = JSON.parse(decodeURIComponent(option.submitOrderForm))
			this.cartList = this.submitOrderForm.items
			
			// #ifdef APP-PLUS
			this.openLists = [{
				image: '../../static/images/zhifubao.png',
				text: '支付宝',
				id: 1
			}, {
				image: '../../static/images/icon_weixin.png',
				text: '微信',
				id: 2
			}, {
				image: '../../static/images/lingqian.png',
				text: '零钱',
				id: 3
			}];
			this.openWay = 1;
			// #endif

			// #ifdef MP-WEIXIN
			this.openLists = [{
				image: '../../static/images/icon_weixin.png',
				text: '微信',
				id: 2
			}, {
				image: '../../static/images/lingqian.png',
				text: '零钱',
				id: 3
			}];
			this.openWay = 2;
			// #endif

			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase();
			if (ua.indexOf('micromessenger') !== -1) {
				this.openLists = [{
					image: '../../static/images/zhifubao.png',
					text: '支付宝',
					id: 1
				}, {
					image: '../../static/images/lingqian.png',
					text: '零钱',
					id: 3
				}, {
					image: '../../static/images/icon_weixin.png',
					text: '微信',
					id: 2
				}];
				this.openWay = 1;
			} else {
				this.openLists = [{
					image: '../../static/images/zhifubao.png',
					text: '支付宝',
					id: 1
				}, {
					image: '../../static/images/lingqian.png',
					text: '零钱',
					id: 3
				}];
				this.openWay = 1;
			}
			
			
			// #endif


		},
		
		
		onShow() {
			uni.$on('address', (res) => {
				this.addrForm = res
				console.log('接收到的地址数据:', res);
				// 处理数据后移除监听（避免重复触发）
				uni.$off('address');
			});
			
			if(!this.addrForm.id){
				this.getAddressList()
			}
		},
		methods: {


			bindclost() {
				this.showPay = false
				uni.reLaunch({
					url: '/shopping/shoppOrder/index'
				})
			},

			selectWay: function(id) {
				this.openWay = id;
			},

			// 计算选中商品总价
			calculateTotal() {
				let total = 0
				this.cartList.forEach(item => {
					if (item.check) {
						total += item.totalPrice * 1 // 转为数字
					}
				})
				this.totalPrice = (total + this.fare).toFixed(2)
			},

			//跳转选择地址页面
			toShoppAddress(id) {
				uni.navigateTo({
					url: '/shopping/shoppAddress/address?id=' + id + '&type=1'
				});
			},


			//下单
			submitOrder() {
				console.log(this.addrForm);
				uni.showToast({
					title: '请稍等...',
					icon: 'loading',
					mask: true, // 关键参数
				})
				if(!this.addrForm.id){
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none',
						mask: true, // 关键参数
					})
					return
				}
				let data = {
					"addrId": this.addrForm.id,
					"note": this.note,
					"orderToken": this.submitOrderForm.orderToken,
					"payPrice": this.totalPrice,
				}
				this.$Request.postJson(`/app/order/submitOrder`, data).then(res => {
					if (res.code == 0 && res.data) {
						this.showPay = true
						this.orderSn = res.data.order.orderSn
					}
					uni.hideLoading();
				});

			},







			//获取运费
			getYunFei() {
				this.$Request.getT('/app/ware/purchase/fare', {
					addrId: this.addrForm.id
				}).then(res => {
					if (res.code == 0 && res.data) {
						this.fare = res.data.fare
						this.calculateTotal()
					}
				});
			},




			//获取默认地址
			getAddressList() {
				this.$Request.getT('/app/member/memberreceiveaddress/addresses').then(res => {
					if (res.code == 0) {
						let a = res.data.find(it => it.defaultStatus)
						if (a) {
							this.addrForm = a
						} else if (res.data.length > 0) {
							this.addrForm = res.data[0]
						}
						this.getYunFei()
					}
				});
			},



			// 支付订单
			pay() {
				if (this.isPay == false) {
					return
				}
				let that = this
				that.showPay = false;
				uni.showModal({
					title: '付款提示',
					content: '确认支付' + that.submitOrderForm.payPrice + '元吗?',
					success: function(re) {
						if (re.confirm) {
							that.isPay = true
							//classify  1app  2公众号 3小程序
							let classify = 1;
							if (that.openWay == 2) { //微信
								// #ifdef MP-WEIXIN
								that.$Request.post("/app/mallOrderPay/wxCombinedOrderPay", {
									orderSn: that.orderSn,
								}).then(red => {

									if (red.code == 0) {
										uni.requestPayment({
											provider: 'wxpay',
											timeStamp: red.data.timeStamp,
											nonceStr: red.data.nonceStr,
											package: red.data.package,
											signType: red.data.signType,
											paySign: red.data.paySign,
											success: function(redd) {
												uni.removeStorageSync('EditAddress')
												uni.showLoading({
													title: '支付成功'
												});
												that.isPay = true
												uni.hideLoading();
												setTimeout(function() {
													// uni.navigateBack();
													//支付完成跳转到购物车
													uni.navigateTo({
														url: '/shopping/shoppMyCard/index'
													})
												}, 1000)
											},
											fail: function(err) {
												that.isPay = true
												uni.hideLoading();
												// that.$queue.showToast(
												// 	'支付失败');
												uni.navigateTo({
													url: '/shopping/shoppMyCard/index'
												})
											}
										});
									} else {
										that.isPay = true
										uni.showToast({
											title: red.msg,
											icon: 'none'
										})
									}
								});
								// #endif

								// #ifdef H5
								let ua = navigator.userAgent.toLowerCase();
								console.log(ua)
								if (ua.indexOf('micromessenger') !== -1) {
									that.$Request.post("/app/wxPay/wxPayOrder", {
										orderId: that.order.ordersId,
										classify: 4
									}).then(red => {
										if (red.code == 0) {
											that.callPay(red.data);
										} else {
											that.isPay = true
											uni.showToast({
												title: red.msg,
												icon: 'none'
											})
										}
									});
								}

								// #endif

								// #ifdef APP-PLUS
								that.$Request.post("/app/wxPay/wxPayOrder", {
									orderId: that.order.ordersId,
									classify: 1
								}).then(red => {
									if (red.code == 0) {
										console.log(red, '+++++++++++++++++++++')
										that.setPayment('wxpay', JSON.stringify(red.data));
									} else {
										that.isPay = true
										uni.showToast({
											title: red.msg,
											icon: 'none'
										})
									}
								});
								// #endif

							} else if (that.openWay == 1) { //支付宝
								// #ifdef H5
								that.$Request.post("/app/aliPay/payOrder", {
									orderId: that.order.ordersId,
									classify: 2
								}).then(red => {
									if (red.code == 0) {
										const div = document.createElement('div')
										div.innerHTML = red.data //此处form就是后台返回接收到的数据
										document.body.appendChild(div)
										document.forms[0].submit()
										that.isPay = true
									} else {
										that.isPay = true
										uni.showToast({
											title: red.msg,
											icon: 'none'
										})
									}
								});
								// #endif
								// #ifdef APP-PLUS
								that.$Request.post("/app/aliPay/payOrder", {
									orderId: that.order.ordersId,
									classify: 1
								}).then(red => {
									if (red.code == 0) {
										that.setPayment('alipay', red.data);
									} else {
										that.isPay = true
										uni.showToast({
											title: red.msg,
											icon: 'none'
										})
									}
								});
								// #endif
							} else if (that.openWay == 3) { //零钱
								that.$Request.post("/app/orders/payMoney", {
									ordersId: that.order.ordersId,
								}).then(res => {
									if (res.code == 0) {
										uni.showToast({
											title: '支付成功'
										})
										that.isPay = true
										setTimeout(function() {
											uni.navigateBack();
										}, 1000)
									} else {
										that.isPay = true
										uni.showToast({
											title: res.msg,
											icon: 'none'
										})
									}
								});
							}

						} else if (re.cancel) {
							that.isPay = true
							uni.navigateTo({
								url: '/shopping/shoppOrder/index'
							})
						}
					}

				})

			},

		},

	}
</script>
<style lang="scss" scoped>
	.cart-page {
		background-color: #f7f7f7;
		min-height: 100vh;
		border-top: 2rpx solid #f4f4f4;

		/* 商品列表 */
		.cart-list {
			margin-top: 20rpx;

			.cu-item {
				background-color: #fff;
				margin-bottom: 20rpx;
				padding: 20rpx;

				/* 店铺信息 */
				.shop-info {
					display: flex;
					align-items: center;

					.shop-name {
						font-size: 28rpx;
						color: #333;
					}

					.arrow {
						margin-left: 10rpx;
						color: #999;
					}
				}

				/* 商品内容 */
				.goods-content {
					display: flex;
					padding: 20rpx 0;
					align-items: center;

					.goods-img {
						width: 160rpx;
						height: 160rpx;
						border-radius: 8rpx;
						margin-right: 20rpx;
					}

					.goods-info-wrap {
						flex: 1;

						.goods-title {
							font-size: 30rpx;
							color: #333;
							line-height: 44rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							/* 文字超出2行省略 */
							overflow: hidden;
						}

						.goods-spec {
							font-size: 28rpx;
							color: #999;
							margin: 10rpx 0;
						}

						.tags {
							display: flex;
							flex-wrap: wrap;
							margin-bottom: 10rpx;

							.cu-tag {
								margin-right: 10rpx;
								margin-bottom: 10rpx;
								font-size: 24rpx;
							}
						}

						.price-section {
							display: flex;
							align-items: center;
							justify-content: space-between;
							margin-bottom: 10rpx;

							.current-price {
								color: #ff6700;
								font-size: 32rpx;
								font-weight: bold;
							}

							.original-price {
								color: #999;
								font-size: 28rpx;
								text-decoration: line-through;
								/* 原价划掉 */
							}

							.discount {
								font-size: 28rpx;
								color: #ff6700;
								margin-right: 20rpx;
							}

							.detail {
								font-size: 28rpx;
								color: #666;
							}
						}

						.coupon-desc {
							font-size: 28rpx;
							color: #ff6700;
						}
					}
				}
			}
		}

		/* 底部操作栏 */
		.bottom-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 140rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			padding: 20rpx 20rpx 60rpx 20rpx;
			border-top: 1px solid #eee;

			.total {
				flex: 1;
				text-align: right;

				.total-price {
					color: #ff6700;
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.settle-btn {
				width: 200rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 40rpx;
				background-color: #ff6700;
				color: #fff;
				font-size: 32rpx;
			}
		}
	}

	.box {
		width: 100%;
		height: 100vh;
		background: rgba(0, 0, 0, 0.7);
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		z-index: 9999;
	}

	.bottbox {
		position: fixed;
		bottom: 0upx;
		left: 0;
		right: 0;
		z-index: 9999;
		background: #ffffff;
	}
</style>